<template>
    <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="其他座席" name="agent">
                <el-cascader
                        ref="cascaderRef"
                        style="width:100%;"
                        popper-class="plus-popover"
                        :options="agentOptions"
                        placeholder="请输入名称或工号"
                        filterable>
                    <template slot-scope="{ node, data }">
                        <div v-if="data.freeNumber >=0">
                            <span>{{ data.label }}</span>
                            <span>({{ data.freeNumber }})</span>
                        </div>
                        <div v-else class="clearfix"  style="cursor:default" @click.stop>
                            <span>{{ data.label }}</span>
                            <span v-if="data.callStatusName">· <span :class="data.callStatus === '0'?'free-status':''">{{ data.callStatus === '0'?'空闲':'忙碌' }}</span></span>
                            <span v-if="data.callStatus === '0'" :class="module==='transfer'?'V7_iconV7tubiao_zhuanyi':'V7_iconV7tubiao_zixun'" class="V7_iconfont  fr" @click.stop="transferAction(data.agentNumber, 'agent', data.label)"></span>
                        </div>
                    </template>
                </el-cascader>
            </el-tab-pane>
            <el-tab-pane label="外线电话" name="outline">
                <el-input v-model="outlineNumber" size="mini" clearable placeholder="请输入手机或完整的区号电话号码" style="width:242px;"></el-input>
                <el-button type="primary" size="mini" class="fr" :disabled="!outlineNumber" @click.stop="transferAction(outlineNumber, 'outline', outlineNumber)">{{module === 'transfer'?'转移':'咨询'}}</el-button>
            </el-tab-pane>
            <el-tab-pane label="语音导航" name="ivr" v-if="module==='transfer'">
                <el-autocomplete
                        style="width:242px;"
                        size="mini"
                        class="inline-input"
                        popper-class="plus-popover"
                        v-model="ivrObj.name"
                        :fetch-suggestions="querySearch"
                        @select="handleSelect"
                        @clear="handleSelect({})"
                        clearable
                        placeholder="请输入语音导航名字">
                    <template slot-scope="{ item }">
                        <div class="name">{{ item.name }}</div>
                    </template>
                </el-autocomplete>
                <el-button type="primary" class="fr" size="mini" :disabled="!ivrObj.nodeId" @click.stop="transferAction(ivrObj.nodeId, 'ivr', ivrObj.name)">转移</el-button>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import { CtiModule } from '@/store/modules/cti/index'
import { isNumber2 } from '@/utils/validate'
import { deepClone } from '@/utils/common'
@Component({
  name: 'TransferPopover',
  filters: {}
})
export default class CallPopover extends Vue {
  [x: string]: any
  @Prop() private module!: string
  private activeName: string = 'agent' // 当前tab选中项
  private outlineNumber: string = '' // 当前填写的外线电话
  private ivrList: any[] = [] // 语音导航的列表
  private ivrObj: object = {
    name: '',
    nodeId: ''
  } // 当前选中的语音导航

  private agentOptions: any[] = []

  private handleClick () {
    if (this.activeName === 'ivr') { // 每次tab切换过来的时候请求服务器的ivr列表 && 不需要遮罩
      this.$getCache('/call/action/general/query', ['ivrList'], false, true, false).then((resp: any) => {
        if (resp && resp.success) {
          this.ivrList = resp.ivrList || []
        }
      })
    }
  }

  private restFrom () {
    this.outlineNumber = ''
    this.ivrObj = { name: '', nodeId: '' }
  }

  public fetchQueueOnlineAgents () {
    this.restFrom()
    CtiModule.CtiCommonAction({ url: '/base/action/agentStatus/getQueueOnlineAgents', method: 'POST', data: {}, hideLoading: true }).then((res: any) => {
      if (res && res.success && res.data) {
        const dataList: any[] = []
        res.data.forEach((item: any) => {
          const itemObj: any = { value: item._id, label: item.name, freeNumber: 0 }
          let itemFreeNum = 0
          const agentArr: any = []
          if (item.members && item.members.length > 0) {
            item.members.forEach((item2: any) => { // 排除技能组内的自己（不能自己咨询或者是转移自己）
              if (item2.agentId !== this.$store.state.common.session.user._id) {
                const item2Obj: any = { value: item2.agentId, label: `${item2.agentName}【${item2.agentNumber}】`, callStatus: item2.callStatus, callStatusName: item2.callStatusName, agentNumber: item2.agentNumber }
                if (item2.callStatus === '0') { // 筛选出空闲的
                  itemFreeNum++
                } else {
                  item2Obj.disabled = true
                }
                agentArr.push(item2Obj)
              } else { // 匹配到是自己
                if (item.members.length === 1) { // 技能组内只有一个人，还是自己，disabled
                  itemObj.disabled = true
                }
              }
            })
          } else {
            itemObj.disabled = true
          }
          itemObj.freeNumber = itemFreeNum
          if (agentArr.length > 0) {
            itemObj.children = agentArr
          }
          dataList.push(itemObj)
        })
        this.agentOptions = dataList
      }
    })
  }

  private transferAction (number, transferType, label) {
    if (transferType === 'outline') { // 转外线号码，校验号码
      if (!isNumber2(number) || !number) { // 不是纯数字 || 没有手机号
        this.$message.error('请输入正确的号码')
        return false
      }
    }
    let url = '/call/action/biz/consult'
    let actionData: any = { consultNumber: number, consultType: transferType, superUniqueId: this.$store.state.cti.superUniqueId }
    if (this.module === 'transfer') {
      url = '/call/action/biz/transfer'
      actionData = { transferNumber: number, transferType }
    }
    CtiModule.CtiCommonAction({ url, method: 'POST', data: actionData }).then((res: any) => {
      if (res && res.success) {
        if (this.module === 'consult') { // 咨询请求成功，操作按钮变更咨询ing
          this.$message('正在为您呼叫咨询中，请等待')
          this.$emit('consultingAgentData', label)
        } else {
          this.$message({ message: `通话已转移至${label}`, type: 'success' })
        }
      }
    })
    const cascaderRef: any = this.$refs.cascaderRef
    cascaderRef.dropDownVisible = false // 收起级联组件的面板
    this.$emit('closePopover')
  }

  private querySearch (queryString, cb) {
    const ivrList = deepClone(this.ivrList)
    const results = queryString ? ivrList.filter(this.createFilter(queryString)) : ivrList
    // 调用 callback 返回建议列表的数据
    cb(results)
  }

  private createFilter (queryString) {
    return (ivrList) => {
      return (ivrList.name.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
    }
  }

  private handleSelect (data) {
    this.ivrObj = data || {}
  }

  get getUpdateQueueAgentArr () {
    return this.$store.state.cti.updateQueueAgentObj || []
  }

  @Watch('getUpdateQueueAgentArr')
  private updateQueueAgentArr (event) {
    if (!event.body || !Array.isArray(event.body)) {
      return
    }
    event.body.forEach((item: any) => { // 遍历事件数组
      if (item.queueList && item.queueList.length > 0) { // 事件推送的有技能组信息
        const tempAgents = deepClone(this.agentOptions)
        tempAgents.forEach((queueItem: any) => {
          if (item.queueList.indexOf(queueItem.value) > -1) { // 根据技能组id先选出技能组
            let agentFlag = false
            let deleteIndex = -1
            if (queueItem.children && queueItem.children.length > 0) { // 技能组内有成员
              queueItem.children.forEach((agentItem: any, index: number) => {
                if (agentItem.value === item.agentId) { // 找到对应的座席,修改对应的状态
                  agentFlag = true
                  if (event.type === 'queueAgentRemove') { // 移除座席信息
                    deleteIndex = index
                    if (agentItem.callStatus === '0') { // 退出登录的时候，是空闲退出的，技能组在线数-1
                      queueItem.freeNumber--
                      console.log(item, queueItem.freeNumber, '=======退出登录了--？')
                    }
                  } else {
                    if (item.callStatus === '0') {
                      queueItem.freeNumber++
                      agentItem.disabled = false
                      console.log(item, queueItem.freeNumber, '=======切换成了空闲++？')
                    } else {
                      if (agentItem.callStatus === '0') { // 上一步状态是空闲，状态变更的时候，才会减1，否则从呼叫中=> 通话中之类的，也会一直减少
                        queueItem.freeNumber--
                        console.log(item, queueItem.freeNumber, '=======切换成忙碌，或者是外呼了--？')
                      }
                      agentItem.disabled = true
                    }
                    agentItem.callStatus = item.callStatus
                    agentItem.callStatusName = item.callStatusName
                  }
                  return false
                }
              })
              if (deleteIndex !== -1) { // 移除技能组内的座席信息（座席退出登录）
                queueItem.children.splice(deleteIndex, 1)
              }
            }
            if (!agentFlag) { // 能找到技能组，但是找不到座席，说明是新登录的座席
              const newData = { value: item.agentId, label: `${item.agentName}[${item.agentNumber}]`, callStatus: item.callStatus, callStatusName: item.callStatusName, agentNumber: item.agentNumber }
              if (!queueItem.children) { // 从无到有
                queueItem.children = [newData]
              } else {
                queueItem.children.push(newData)
              }
              if (item.callStatus === '0') {
                queueItem.freeNumber++
                console.log(item, queueItem.freeNumber, '=======新座席登录了++？')
              }
            }
            return false
          }
        })
        this.agentOptions = tempAgents
      }
    })
  }
}
</script>
<style scoped lang="stylus">
    .free-status
      color $c-main
    .V7_iconfont
       margin-left 10px
       cursor pointer
</style>
